﻿using System.Collections.Specialized;
using System.Text;
using System.IO;
using System.Xml;

namespace WeiBeeCommon.Core
{
    public class OAuthSina : OAuthBase
    {
        public OAuthSina()
        {
            Title = @"新浪微博";
            ConsumerKey = "1758087936";
            ConsumerSecret = "bed16662269e81094dff3bfbe70af158";
            RequestToken = "http://api.t.sina.com.cn/oauth/request_token";
            Authorize = "http://api.t.sina.com.cn/oauth/authorize";
            AccessToken = "http://api.t.sina.com.cn/oauth/access_token";
            Jpeg = "image/pjpeg";
        }

        protected override void MultipartformBody(NameValueCollection qs, byte[] boundarybytes, byte[] boundarybytes1, Stream requestStream, string formdataTemplate)
        {
            requestStream.Write(boundarybytes1, 0, boundarybytes1.Length);
            string key = "status";
            string formitem = string.Format(formdataTemplate, key, qs[key]);
            byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
            requestStream.Write(formitembytes, 0, formitembytes.Length);
            requestStream.Write(boundarybytes, 0, boundarybytes.Length);
            string formitem1 = string.Format(formdataTemplate, "source", ConsumerKey);
            byte[] formitembytes1 = Encoding.UTF8.GetBytes(formitem1);
            requestStream.Write(formitembytes1, 0, formitembytes1.Length);
            requestStream.Write(boundarybytes, 0, boundarybytes.Length);
        }

        public override void XAuthLogin(string username, string password)
        {
            string authLink = string.Format("{0}&userId={1}&passwd={2}&oauth_callback=xml", AuthorizationLinkGet(), username, password);
            string html = Utility.WebRequest(Method.POST, authLink, null);
            AccessTokenGet(Token, ParseHtml(html));
        }

        private string ParseHtml(string html)
        {
            var xmldocument = new XmlDocument();
            xmldocument.LoadXml(html);
            return xmldocument.GetElementsByTagName("oauth_verifier")[0].InnerText;
        }
    }
}
